<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" destroy-on-close @closed="$emit('closed')" :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true" fullscreen>
        <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="130" ref="dialogForm" style="height: calc(100vh - 100px);overflow-y: auto;">
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6" v-if="mode != 'add'">
                    <el-form-item label="采购单号" prop="input_type">
                        <el-input v-model="form.purchase_code" placeholder="采购单号" readonly></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6">
                    <el-form-item label="采购计划" prop="purchase_code">
                        <el-input v-model="info.purchase_code" placeholder="请输入采购计划" readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="地区" prop="area_id">
						<el-select v-model="form.area_id" placeholder="请选择" filterable clearable>
							<el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="下单日期" prop="purchase_date">
						<el-date-picker v-model="form.purchase_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%" @change="processChange"/>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="交货日期" prop="deliver_date">
                        <el-date-picker v-model="form.deliver_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6">
					<el-form-item label="供应商" prop="apply_id">
						<!-- <el-input v-model="info.apply_name" placeholder="供应商" readonly></el-input> -->
                        <el-select v-model="form.apply_id" placeholder="请选择" filterable @change="applyChange(form.apply_id)" :disabled="form.purchase_plan_id != ''">
							<el-option v-for="item in applyList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="需方" prop="buyer_id">
                        <el-input v-model="buyer_name" placeholder="请选择需方" readonly @click="checkBuyer"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="品名" prop="goods_name">
						<el-input v-model="form.goods_name" placeholder="品名" readonly @click="checkShop"></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="订单类型" prop="plan_type">
						<!-- <el-input v-model="info.plan_type_text" placeholder="订单类型" readonly></el-input> -->
                        <el-select v-model="form.plan_type" placeholder="请选择" clearable :disabled="form.purchase_plan_id != ''">
							<el-option label="白坯" :value="1"></el-option>
							<el-option label="半成品" :value="2"></el-option>
							<el-option label="成品" :value="3"></el-option>
						</el-select>
					</el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6">
                    <el-form-item label="联系人" prop="linkman">
						<el-input v-model="applyInfo.linkman" placeholder="联系人" readonly></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="联系方式" prop="mobile">
						<el-input v-model="applyInfo.mobile" placeholder="联系方式" readonly></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="克重" prop="weight">
						<el-input v-model="form.weight" placeholder="克重" clearable type="number" @mousewheel.prevent>
                            <template #append>克/米</template>
                        </el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="单价" prop="price">
						<el-input v-model="form.price" placeholder="单价" clearable type="number" @mousewheel.prevent>
                            <template #append>元/米</template>
                        </el-input>
					</el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6">
                    <el-form-item label="备注" prop="remark">
						<el-input v-model="form.remark" placeholder="备注" clearable></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-input v-model="form.remark2" placeholder="" clearable></el-input>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="计划数量" prop="plan_num">
						<el-input v-model="info.plan_num" placeholder="计划数量" readonly>
                            <template #append>匹</template>
                        </el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="已采购" prop="purchase_number">
						<el-input v-model="info.purchase_number" placeholder="已采购" readonly>
                            <template #append>匹</template>
                        </el-input>
					</el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6">
                    <el-form-item label="批号" prop="batch_num">
						<el-input v-model="form.batch_num" placeholder="批号" clearable :readonly="form.purchase_plan_id != ''"></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6"></el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="模版" prop="template_id">
						<el-select v-model="form.template_id" placeholder="请选择" filterable clearable @change="templateChange(form.template_id)">
							<el-option v-for="item in templateList" :key="item.id" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="门幅" prop="door">
						<el-input v-model="form.door" placeholder="门幅" clearable type="number" @mousewheel.prevent>
                            <template #append>米</template>
                        </el-input>
					</el-form-item>
                </el-col>
            </el-row>
            <el-col :span="12">
                <el-form-item>
                    <el-input v-model="form.content" :rows="7" clearable type="textarea"></el-input>
                </el-form-item>
            </el-col>

            <!-- 样本 -->
            <el-form-item>
                <el-link type="primary" style="margin-right: 20px" :underline="false" @click="checkSample(1)">样本选择</el-link>
                <div style="margin-right: 20px;">
                    <el-image v-if="sample_image" style="width: 100px; height: 100px; border-radius: 5px;" :src="sample_image" :preview-src-list="[sample_image]" preview-teleported="true" hide-on-click-modal align="center"></el-image>
                    <div>{{sample_name}}</div>
                </div>
                <el-checkbox v-model="select_all" size="large" label="全选" @change="changeAll(select_all)" v-if="sampleList.length > 0" />
                <el-checkbox v-for="(item,index) in sampleList" :key="index" v-model="item.show" size="large" :label="item.name" @change="sampleChange(item)" />
            </el-form-item>

            <!-- 花型 -->
            <el-form-item>
                <el-link type="primary" style="margin-right: 20px" :underline="false" @click="checkFlower">花型选择</el-link>
                <el-tag v-for="(item,index) in flowerList" :key="index" :closable="mode != 'show'" type="info" style="margin-right: 20px" @close="delTag(index)">
                    <el-popover placement="top-start" :width="500" trigger="hover">
                        <el-image v-if="item?.flower_image" style="width: 400px; height: 400px; border-radius: 5px;" :src="item.flower_image" :preview-src-list="[item.flower_image]" preview-teleported="true" hide-on-click-modal align="center"></el-image>
                        <template #reference>
                            {{ item.flower }}
                        </template>
                    </el-popover>
                </el-tag>
            </el-form-item>
            <el-form-item label-width="20">
                <sc-form-table class="formtable" ref="table" v-model="form.order_detail" hideAdd hideDelete placeholder="暂无数据" :show-summary="mode != 'show'" :summary-method="handleSummary" :objectSpanMethod="objectSpanMethod" :cellStyle="cellStyle">
                    <el-table-column label="花型" align="center" prop="flower">
                        <template #default="scope">
                            {{scope.row.flower}}
                        </template>
                    </el-table-column>
                    <el-table-column v-for="(item,index) in table_list" :key="index" :label="item.name" :prop="item.name" align="center">
                        <template #header>
                            <div style="display: flex;align-items: center;justify-content: center;">
                                <el-popover placement="top" :width="200" trigger="click" v-model="popover">
                                    <template #reference>
                                        <div @click="getFocus(item.name)">{{item.name}}</div>
                                    </template>
                                    <div style="display: flex;align-items: center;">
                                        <el-input v-model="all_set_number" type="number" :ref="item.name + '_color'" @mousewheel.prevent @input="color_input(item,$event)"></el-input>
                                    </div>
                                </el-popover>
                            </div>
                        </template>
                        <template #default="scope">
                            <div v-if="mode != 'show'">
                                <el-input v-model="scope.row[item.name]" type="number" @mousewheel.prevent placeholder="" @focus="common.inputFocus($event)" @input="totalComputed(scope.row)" class="inputDeep"></el-input>
                            </div>
                            <div v-else>
                                {{scope.row.ware_obj[item.prop]}}/{{scope.row.total_obj[item.prop]}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="订单数" align="center" prop="number" v-if="mode != 'show'">
                        <template #header>
                            <div style="display: flex;align-items: center;justify-content: center;">
                                <el-popover placement="top" :width="200" trigger="click" v-model="popover">
                                    <template #reference>
                                        <div @click="getFocusNumber">订单数</div>
                                    </template>
                                    <div style="display: flex;align-items: center;">
                                        <el-input v-model="set_number" type="number" ref="numberInput" @mousewheel.prevent @input="number_input"></el-input>
                                    </div>
                                </el-popover>
                            </div>
                        </template>
                        <template #default="scope">
                            <el-input v-model="scope.row.number" type="number" @mousewheel.prevent placeholder="" @focus="common.inputFocus($event)" @input="totalComputed(scope.row)" class="inputDeep"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="合计" align="center" prop="total_number"></el-table-column><!--  v-if="mode != 'show'" -->
                    <el-table-column label="备注" align="center" width="200" v-if="mode != 'show'">
                        <template #default="scope">
                            <el-input v-model="scope.row.remark" @mousewheel.prevent placeholder="备注" clearable class="inputDeep"></el-input>
                        </template>
                    </el-table-column>
                </sc-form-table>
            </el-form-item>
        </el-form>
        <!-- <template #footer>
            <el-button @click="visible=false">取 消</el-button>
            <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit(0)">保 存</el-button>
        </template> -->
        <el-footer style="text-align: right;position: fixed;bottom: 0;right: 0;left: 0;padding: 10px 20px;background: #fff;border-top: 1px solid #eee;">
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(0)">保存</el-button>
		</el-footer>
        <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsBack" @closed="dialog.goods = false" :query="{is_show: 1}"></select-goods>
        <select-sample v-if="dialog.sample" ref="sampleDialog" @success="sampleBack" @closed="dialog.sample = false" :query="{apply_id: form.apply_id,goods_id: form.goods_id,type: 1}"></select-sample>
        <select-flower v-if="dialog.flower" ref="flowerDialog" @success="flowerBack" @closed="dialog.flower = false"></select-flower>
        
        <buyer-list v-if="dialog.buy" ref="buyDialog" @success="buyBack" @closed="dialog.buy = false"></buyer-list>
        
        <shop-apply v-if="dialog.shop" ref="shopDialog" @success="shopBack" @closed="dialog.shop = false" :query="{apply_id: form.apply_id}"></shop-apply>
    </el-dialog>
</template>

<script>

import selectGoods from '@/views/basic/goods/selectGoods.vue';
import SelectSample from '../../selectSample.vue';
import SelectFlower from '@/views/basic/apply/selectFlower.vue';
import BuyerList from '@/views/basic/buyer/buyerList.vue';
import shopApply from '@/views/basic/apply/shopApply.vue';
export default {
    emits: ['success', 'closed'],
    components: { selectGoods, SelectSample, SelectFlower, BuyerList, shopApply,},
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '新增采购单',
                copy: '新增采购单',
                edit: '编辑采购单',
                show: '查看采购单',
            },
            visible: false,
            isSaveing: false,
            form: {
                id: "",
                purchase_plan_id: "",
                purchase_code: "",
                area_id: "",
                apply_id: "",
                goods_id: "",
                goods_name: "",
                purchase_staff: this.$TOOL.data.get("USER_INFO").admin_id,
                purchase_date: this.moment().format('YYYY-MM-DD'),
                deliver_date: this.moment().add(30, 'days').format('YYYY-MM-DD'),
                remark: "",
                remark2: "",
                total_num: "",
                deliver_num: "",
                // customer_pro_sample_id: "",
                select_sample_param: "",
                select_colors: "",
                select_flower_param: [],
                price: "",
                weight: "",
                content: "",
                door: "2.8",
                batch_num: "",
                template_id: "",
                order_detail: [],
                buyer_id: "",
                plan_type: "",
            },
            info: {
                purchase_code: "",
                apply_name: "",
                plan_type_text: "",
                linkman: "",
                mobile: "",
                plan_num: "",
                purchase_number: "",
                batch_num: "",
            },
            rules: {
                area_id: [{required: true, message: '请选择地区'},],
                apply_id: [{required: true, message: '请选择供应商'},],
                goods_name: [{required: true, message: '请选择品名'},],
                plan_type: [{required: true, message: '请选择订单类型'},],
                batch_num: [{required: true, message: '请输入批号'},],
            },
            dialog: {
                goods: false,
                sample: false,
                flower: false,
                buy: false,
                shop: false,
            },
            areaList: [],
            templateList: [],
            select_all: false,
            sampleList: [],
            table_list: [],
            flowerList: [],
            edit_table_list: [],
            all_set_number: "",
            set_number: "",
            buyer_name: "",
            sample_name: "",
            sample_image: "",
            
            applyList: [],
            applyInfo: {
                linkman: "",
                mobile: "",
                address: "",
                apply_name: "",
            },
        }
    },
    mounted() {
		this.getArea();
		this.getTemplate();
		this.getApply();
    },
    created() {
        // this.color_input = this.common.debounce(this.color_input, 1000);
	},
    methods: {
        cellStyle(row){
            let cellStyle = '';
            if(row.column.label != '花型' && row.column.label != '备注' && row.column.label != '合计' && row.column.fixed != 'left'){
                cellStyle = {backgroundColor:'#FFF'}
            }else {
                cellStyle = {backgroundColor:'#f4f4f5'}
            }
            return cellStyle
        },
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        //表单提交方法
        submit() {
            let flower = []
            this.flowerList.map(item=>{
                flower.push({
                    flower: item.flower,
                    flower_image: item.flower_image,
                })
            })
            this.form.select_flower_param = flower
            let sample = []
            this.sampleList.map(item=>{
                if(item.show){
                    sample.push(item.name)
                }
            })
            this.form.select_colors = sample.join(',')
            let count = 0
            this.form.order_detail.map(item=>{
                count = Number(item.total_number) + count
            })
            this.form.total_num = count
            console.log('this.form :>> ', this.form);
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    var res = [];
                    if (this.form.id) {
                        res = await this.$API.business.purchase.order.edit.post(this.form);
                    } else {
                        res = await this.$API.business.purchase.order.add.post(this.form);
                    }
                    this.isSaveing = false;
                    if (res.code == 1) {
                        this.visible = false;
                        this.$emit('success', this.form, this.mode)
                        this.$message.success("操作成功")
                    } else {
                        this.$alert(res.message, "提示", {type: 'error'})
                    }
                }
            })
        },
        //表单注入数据
        async setData(data,val) {
            if(!val){
                this.form.id = data.id
                this.form.purchase_code = data.purchase_code
            }
            var res = await this.$API.business.purchase.order.detail.get({id: data.id});
            this.form.purchase_plan_id = res.data.purchase_plan_id
            this.form.area_id = res.data.area_id
            this.form.apply_id = res.data.apply_id
            this.form.buyer_id = res.data.buyer_id
            this.buyer_name = res.data.buyer?.buyer_name
            this.applyInfo.apply_name = res.data.apply && res.data.apply.apply_name
            this.applyInfo.linkman = res.data.apply && res.data.apply.linkman
            this.applyInfo.mobile = res.data.apply && res.data.apply.mobile
            this.form.plan_type = res.data.plan_type
            this.form.goods_id = res.data.goods_id
            this.form.goods_name = res.data.goods_Name
            this.info.purchase_code = res.data.Plan && res.data.Plan.purchase_code
            this.info.plan_num = res.data.Plan && res.data.Plan.plan_num
            this.info.purchase_number = res.data.Plan && res.data.Plan.purchase_number
            this.form.purchase_staff = res.data.purchase_staff
            this.form.purchase_date = res.data.purchase_date
            this.form.remark = res.data.remark
            this.form.remark2 = res.data.remark2
            this.form.total_num = res.data.total_num
            this.form.deliver_num = res.data.deliver_num
            this.form.deliver_date = res.data.deliver_date
            // this.form.customer_pro_sample_id = res.data.customer_pro_sample_id
            this.sample_name = res.data.select_sample_param?.title 
            this.sample_image = res.data.select_sample_param?.image
            this.form.select_sample_param = res.data.select_sample_param
            this.form.select_colors = res.data.select_colors
            this.form.select_flower_param = res.data.select_flower_param
            this.form.price = res.data.price
            this.form.weight = res.data.weight
            this.form.content = res.data.content
            this.form.door = res.data.door
            this.form.batch_num = res.data.batch_num
            this.form.template_id = res.data.template_id
            this.form.select_colors = res.data.select_colors
            let sample = []
            let color = res.data.select_sample_param.colors.split(',')
            color.map(item=>{
                sample.push({
                    show: res.data.select_colors.includes(item),
                    name: item
                })
            })
            this.sampleList = sample
            this.flowerList = res.data.select_flower_param
            var array = []
            let colorName = []
            res.data.order_detail[0].color_data.map(item=>{
                sample.map(item1=>{
                    if(item1.name == item.color_name){
                        if(item1.show){
                            colorName.push({
                                name: item.color_name,
                                number: item.number
                            })
                        }
                    }
                })
            })
            this.table_list = colorName
            res.data.order_detail.map(item=>{
                const dynamicFields = Object.fromEntries(
                    this.table_list.map(item1 => {
                        const colorItem = item.color_data.find(c => c.color_name === item1.name);
                        return [item1.name, colorItem?.number || 0];
                    })
                );
                let data = {
                    color_data: item.color_data,
                    flower: item.flower,
                    number: item.order_count,
                    remark: item.remark,
                    total_number: item.total_count,
                    ware_obj: {},
                    total_obj: {},
                    ...dynamicFields
                }
                // if(!val){
                //     data.id = item.id
                // }
                array.push(data)
            })
            this.form.order_detail = array
            this.updateTableList()
        },
        // 添加获取数据
        getData(data){
            this.form.purchase_plan_id = data.id
            this.form.apply_id = data.apply_id
            this.form.goods_id = data.goods_id
            this.info.purchase_code = data.purchase_code
            this.applyInfo.apply_name = data.apply && data.apply.apply_name
            this.applyInfo.linkman = data.apply && data.apply.linkman
            this.applyInfo.mobile = data.apply && data.apply.mobile
            this.form.goods_name = data.goods && data.goods.name
            this.form.plan_type = data.plan_type
            this.info.plan_num = data.plan_num
            this.info.purchase_number = data.purchase_number
            this.form.batch_num = data.batch_num
            this.form.weight = data.weight
            this.form.price = data.price
            this.form.buyer_id = data.buyer_id
            this.buyer_name = data.buyer?.buyer_name
        },
        // 地区列表
		async getArea() {
			var res = await this.$API.basic.area.all.get();
			this.areaList = res.data
		},
        // 模版列表
		async getTemplate() {
			var res = await this.$API.basic.print.all.get();
			this.templateList = res.data
		},
        // 供应商列表
		async getApply() {
			var res = await this.$API.basic.apply.all.get({type: 1});
			this.applyList = res.data
		},
        applyChange(e){
            let apply = this.applyList.find(item => item.apply_id == e)
            this.applyInfo.linkman = apply.linkman
            this.applyInfo.mobile = apply.mobile
            this.applyInfo.address = apply.address
            this.applyInfo.apply_name = apply.apply_name
            this.form.goods_id = ""
            this.form.goods_name = ""
            
        },
        templateChange(e){
            let template = this.templateList.find(item => item.id == e)
            this.form.content = template.content
        },


        // 选择商品
        checkShop(){
            if(this.form.purchase_plan_id) return
            if(!this.form.apply_id) return this.$message.error('请选择供应商')
            let row = {
                apply_id: this.form.apply_id,
                apply_name: this.applyInfo.apply_name
            }
            this.dialog.shop = true
            this.$nextTick(() => {
                this.$refs.shopDialog.open('add').setData(row,'select')
            })
        },
        // 选择商品返回
        shopBack(data){
            this.form.goods_id = data.goods_id
            this.form.goods_name = data.goods_name
        },
        // 样本选择
        checkSample(e){
            if(this.mode == 'show') return
            if(!this.form.goods_id) return this.$message.error('请选择品名')
            this.dialog.sample = true
            this.$nextTick(() => {
                this.$refs.sampleDialog.open('add').setData(e)
            })
        },
        // 样本返回
        sampleBack(data){
            this.sample_name = data.title
            this.sample_image = data.image
            // this.form.customer_pro_sample_id = data.id
            let array = []
            let color = data.colors.split(',')
            color.map(item=>{
                array.push({
                    show: false,
                    name: item
                })
            })
            this.sampleList = array
            this.select_all = false
            this.table_list = []
        },
        // 样本全选
        changeAll(e){
            this.sampleList.map(item=>{
                item.show = e
            })
            this.updateTableList();
        },
        // 样本单选
        sampleChange(e){
            if(e.show == false){
                this.select_all = false
            }
            this.updateTableList();
        },
        updateTableList() {
            this.table_list = this.sampleList.filter(item => item.show)
            .map(item => ({
                name: item.name,
                prop: item.name
            }));
            this.form.order_detail = this.form.order_detail.map(row => {
                console.log('row :>> ', row);
                const newRow = { ...row };
                // this.table_list.forEach(col => {
                //     newRow[col.prop] = newRow[col.prop] || 0;
                // });
                this.table_list.forEach(col => {
                    newRow[col.prop] = newRow[col.prop] || 0;
                    if(this.mode == 'show'){
                        newRow.color_data.map(item1=>{
                            if(item1.color_name == col.prop){
                                newRow.ware_obj[col.prop] = item1.ware_number,
                                newRow.total_obj[col.prop] = Number(item1.number) * Number(row.number)
                            }
                        })
                    }
                });
                console.log('newRow :>> ', newRow);
                this.totalComputed(newRow)
                return newRow;
            });
        },
        // 选择花型
        checkFlower(){
            if(!this.form.goods_id) return this.$message.error('请选择品名')
            let query = {
                apply_id: this.form.apply_id,
                goods_id: this.form.goods_id,
                is_select: this.flowerList.map(item => item.flower)
            }
            this.dialog.flower = true
            this.$nextTick(() => {
                this.$refs.flowerDialog.open('add').setData(query)
            })
        },
        // 花型返回
        flowerBack(data){
            console.log('花型 :>> ', data);
            let array = []
            data.map(item =>{
                let exist = this.common.isExist(item.flower_image, this.flowerList, 'flower_image')
                if (exist) {
                    return
                }
                array.push({
                    flower: item.flower,
                    flower_image: item.flower_image,
                    number: 1
                })
            })
            this.flowerList = [...this.flowerList, ...array]
            this.form.order_detail = [...this.form.order_detail, ...array]
        },
        // 删除花型
        delTag(index){
            this.flowerList.splice(index,1)
            this.form.order_detail.splice(index,1)
            // this.$confirm(`确定删除吗？`, '提示', {
            //     type: 'warning'
            // }).then(() => {
            //     this.flowerList.splice(index,1)
            //     this.form.order_detail.splice(index,1)
            // }).catch(() => {})
        },
        totalComputed(row){
            let count = 0
            this.table_list.map(item=>{
                count = Number(row[item.name]) + count
            })
            if(count && row.number){
                row.total_number = count * Number(row.number)
            }
        },
        handleSummary({ columns, data }) {
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '';
                    return;
                }
                if (index === 1) {
                    sums[index] = '合计';
                    return;
                }
                
                // 检查是否为订单数列
                if (column.property === 'number') {
                    // 订单数列的合计可以显示平均值或者空，根据业务需求
                    // 这里选择计算所有行订单数的总和
                    sums[index] = data.reduce((sum, row) => {
                        return sum + (row.number && !isNaN(Number(row.number)) ? Number(row.number) : 0);
                    }, 0);
                    return;
                }
                
                // 检查是否为合计数量列（total_number）
                if (column.property === 'total_number') {
                    // 计算所有颜色数量乘以各自行订单数的总和
                    let total = 0;
                    // 获取所有颜色列的property
                    const colorProperties = this.table_list.map(item => item.name);
                    // 遍历数据，计算每一行的颜色总和乘以该行的订单数
                    data.forEach(row => {
                        const rowOrderNumber = row.number && !isNaN(Number(row.number)) ? Number(row.number) : 0;
                        let rowColorSum = 0;
                        colorProperties.forEach(prop => {
                            if (row[prop] && !isNaN(Number(row[prop]))) {
                                rowColorSum += Number(row[prop]);
                            }
                        });
                        // 累加到总计
                        total += rowColorSum * rowOrderNumber;
                    });
                    sums[index] = total;
                } 
                // 检查是否为颜色列（通过table_list判断）
                else if (this.table_list.some(item => item.name === column.property)) {
                    // 对于颜色列，合计值为该列每行的值乘以该行的订单数，然后累加
                    sums[index] = data.reduce((total, row) => {
                        const rowOrderNumber = row.number && !isNaN(Number(row.number)) ? Number(row.number) : 0;
                        const colorValue = row[column.property] && !isNaN(Number(row[column.property])) ? Number(row[column.property]) : 0;
                        return total + (colorValue * rowOrderNumber);
                    }, 0);
                }
                else if(data.some(row => row[column.property])){
                    // 其他列保持原有逻辑
                    const values = data.map(row => Number(row[column.property]) || 0);
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        return !isNaN(value) ? prev + value : prev;
                    }, 0);
                } else {
                    sums[index] = '';
                }
            });
            return sums;
        },
        objectSpanMethod(row){
            if (row.columnIndex === 1) {
                if (row.rowIndex % 2 === 0) {
                    return {
                        rowspan: 2,
                        colspan: 1,
                    }
                } else {
                    console.log(222);
                    return {
                        rowspan: 0,
                        colspan: 0,
                    }
                }
            }
        },

        processChange(e){
            this.form.deliver_date = this.moment(e).add(30, 'days').format('YYYY-MM-DD')
        },

        // 批量设置数量
        color_input(color,e){
            this.form.order_detail.map(item=>{
                item[color.name] = e
                this.totalComputed(item)
            })
            // this.all_set_number = ""
        },

        // 选择需方
        checkBuyer(){
            this.dialog.buy = true
            this.$nextTick(() => {
                this.$refs.buyDialog.open('add').setData(1)
            })
        },
        // 需方返回
        buyBack(data){
            this.form.buyer_id = data.id
            this.buyer_name = data.buyer_name
        },

        getFocus(item){
            this.all_set_number = ""
            let e = `${item}_color`
            setTimeout(()=>{ 
                this.$nextTick(()=>{
                    this.$refs[e][0].focus()
                })
            },100)
        },
        getFocusNumber(){
            this.set_number = ""
            setTimeout(()=>{ 
                this.$nextTick(()=>{
                    this.$refs.numberInput.focus()
                })
            },100)
        },
        number_input(e){ 
             this.form.order_detail.map( item =>{
                item.number = e
                this.totalComputed(item);
            })
        },
    }
}
</script>

<style lang="scss" scoped>
:deep(.el-input input[type="number"]::-webkit-outer-spin-button),   
:deep(.el-input input[type="number"]::-webkit-inner-spin-button) {
   -webkit-appearance: none;
   margin: 0;   
}
   
:deep(.el-input input[type="number"]) {
   -moz-appearance: textfield;
}
.inputDeep {
    .el-input__inner {
        cursor: default !important;
        text-align: center;
    }
    :deep(.el-input__wrapper) {
        box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
        height: 20px;
        background: transparent;
        cursor: default;
        .el-input__inner {
            cursor: default !important;
            text-align: center;
        }
    }
}
</style>
